﻿using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AduSkin.Controls.Metro;
using HsServerHa.Common.Auth;
using HsServerHa.Core.Http;
using HsServerHa.Entity.Models;
using HsServerHa.UserControls.Dialog;
using HsServerHa.Utility.HttpHelper;
using HsServerHa.Utility.SQLite;
using HsServerHa.WinPage;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;

namespace HsServerHa.ViewModel
{
    public class AlarmPushManageViewModel : ObservableObject
    {
        public AlarmPushManageViewModel() {
            InitData();
            AddCommand = new RelayCommand(addFun);
            QueryCommand = new RelayCommand(InitData);
            DelCommand = new RelayCommand<object>(DelFun);
            UpdateCommand = new RelayCommand<object>(UpdateFun);

            WeakReferenceMessenger.Default.Register<ValueChangedMessage<string>, string>(this, "RefreshAlarm", (r, message) =>
            {
                if (message != null)
                {
                    if (message.Value == "刷新报警数据")
                    {
                        InitData();
                    }
                }
            });
        }
        public void InitData()
        {

            List<AlarmPushManageEntity> list = SQLiteHelper.Table<AlarmPushManageEntity>().ToList();

            AlarmList = new ObservableCollection<AlarmPushManageEntity>(list);
        }

        public ObservableCollection<AlarmPushManageEntity> alarmList { get; set; }
        public ObservableCollection<AlarmPushManageEntity> AlarmList
        {
            get { return alarmList; }
            set
            {
                alarmList = value;
                OnPropertyChanged("AlarmList");
            }
        }

        public void addFun()
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }

            #endregion
            AlertTemp alertTempJoinMaster = new AlertTemp(new AddAlarmPush(), "添加报警推送信息", "500", "800");
            alertTempJoinMaster.ShowDialog();
        }
        public void UpdateFun(object obj)
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }

            #endregion
            AlertTemp alertTempJoinMaster = new AlertTemp(new UpdateAlarmPush(long.Parse(obj.ToString())), "修改报警推送信息", "500", "800");
            alertTempJoinMaster.ShowDialog();
        }
        public async void DelFun(object obj)
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }

            #endregion
            MessageBoxResult dr = AduMessageBox.ShowOKCancel($"你确定删除吗？", "系统提示!", "确定", "取消");
            if (dr == MessageBoxResult.OK)
            {
                var id = obj.ToString();
                var firstPro = AlarmList.FirstOrDefault(x => x.Id == long.Parse(id));

                if (firstPro == null)
                {
                    AduMessageBoxs.Show("数据不存在，请检查");
                    LoggerHelper.SetInfo("数据不存在->查询ID为：" + id, "启动程序管理");
                    return;
                }
                //var dtBind = DbHelperSQLite.Query("select  * from MasterSlaveBind")?.Tables?[0];
                //var bindList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtBind);

                var bindList = await SQLiteHelper.TableAsync<MasterSlaveBindEntity>().ToListAsync().ConfigureAwait(false);
                var bindFirst = bindList?.FirstOrDefault();
                if (bindFirst == null)
                {
                    AduMessageBoxs.Show("程序配置有误，请初始化配置");
                    LoggerHelper.SetInfo("删除失败->程序配置有误，请初始化配置", "启动程序管理");
                    return;
                }
                var result = new HttpResponseResultModel<object>();
                if (App.isMaster.Value)
                {
                    #region 删除从机数据
                    var slavePath = $"http://{bindFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(slavePath +
                   (ConfigurationManager.AppSettings["postDelAlarmPushData"]?.ToString() ?? "postDelAlarmPushData"), JsonConvert.SerializeObject(new ProgramManageEntity { ProgramKey = firstPro.ProgramKey }));

                    #endregion
                }
                else
                {
                    #region 删除主机数据
                    var masterPath = $"http://{App.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(masterPath +
                   (ConfigurationManager.AppSettings["postDelAlarmPushData"]?.ToString() ?? "postDelAlarmPushData"), JsonConvert.SerializeObject(new ProgramManageEntity { ProgramKey = firstPro.ProgramKey }));

                    #endregion
                }

                if (result == null)
                {
                    AduMessageBoxs.Show("删除失败！");
                    LoggerHelper.SetInfo("删除失败:" + JsonConvert.SerializeObject(firstPro), "启动程序管理");
                    return;
                }
                if (!result.IsSuccess)
                {
                    AduMessageBoxs.Show("删除失败！");
                    LoggerHelper.SetInfo("删除失败:" + JsonConvert.SerializeObject(firstPro), "启动程序管理");
                    return;
                }

                //SQLiteHelper.Delete(firstPro);
                SQLiteHelper.ExecuteSql($"delete from AlarmPushManage where ProgramKey='{firstPro.ProgramKey}' ");
                InitData();
                AduMessageBoxs.Show("删除成功！");
                LoggerHelper.SetInfo("删除了程序数据:" + JsonConvert.SerializeObject(firstPro), "启动程序管理");
                return;



            }

        }
        public RelayCommand AddCommand { get; set; }
        public RelayCommand QueryCommand { get; set; }
        public RelayCommand<object> DelCommand { get; set; }
        public RelayCommand<object> UpdateCommand { get; set; }
    }
}
